/**
 * 分段树类
 *
 * @author Kevin
 * @date 2018-12-25
 */
public class SegmentTree<E> {

    /**
     * 分段树
     */
    private E[] tree;

    /**
     * 分段树数据
     */
    private E[] data;

    /**
     * 合并
     */
    private Merger<E> merger;

    public SegmentTree(E[] arr, Merger<E> merger) {
        this.merger = merger;

        this.data = (E[]) new Object[arr.length];
        for (int i = 0; i < arr.length; i++) {
            this.data[i] = arr[i];
        }

        this.tree = (E[]) new Object[4 * arr.length];
        buildSegmentTree(0, 0, arr.length - 1);
    }

    /**
     * 在treeIndex的位置创建表示区间[lelft...right]的线段树
     *
     * @param treeIndex
     * @param left
     * @param right
     */
    private void buildSegmentTree(int treeIndex, int left, int right) {
        if (left == right) {
            this.tree[treeIndex] = this.data[right];
            return;
        }

        int leftTreeIndex = leftChild(treeIndex);
        int rightTreeIndex = rightChild(treeIndex);

        int mid = left + (right - left) / 2;
        buildSegmentTree(leftTreeIndex, left, mid);
        buildSegmentTree(rightTreeIndex, mid + 1, right);

        this.tree[treeIndex] = this.merger.merge(this.tree[leftTreeIndex], this.tree[rightTreeIndex]);
    }

    public E query(int queryLeft, int queryRight) {
        if (queryLeft < 0 || queryLeft >= this.data.length
                || queryRight < 0 || queryRight >= this.data.length
                || queryLeft > queryRight) {
            throw new IllegalArgumentException("Index is illegal.");
        }

        return query(0, 0, this.data.length - 1, queryLeft, queryRight);
    }

    /**
     * 在以treeIndex为根的线段树中[left...right]的范围里，搜索区间[queryLeft...queryRight]的值
     *
     * @param treeIndex
     * @param left
     * @param right
     * @param queryLeft
     * @param queryRight
     * @return
     */
    private E query(int treeIndex, int left, int right, int queryLeft, int queryRight) {
        if (left == queryLeft && right == queryRight) {
            return this.tree[treeIndex];
        }

        int mid = left + (right - left) / 2;
        // treeIndex的节点分为[left...mid]和[mid+1...right]两部分
        int leftTreeIndex = leftChild(treeIndex);
        int rightTreeIndex = rightChild(treeIndex);

        if (queryLeft >= mid + 1) {
            return query(rightTreeIndex, mid + 1, right, queryLeft, queryRight);
        } else if (queryRight <= mid) {
            return query(leftTreeIndex, left, mid, queryLeft, queryRight);
        }

        E leftResult = query(leftTreeIndex, left, mid, queryLeft, mid);
        E rightResult = query(rightTreeIndex, mid + 1, right, mid + 1, queryRight);

        return this.merger.merge(leftResult, rightResult);
    }

    /**
     * 将index位置的值更新为e
     *
     * @param index
     * @param e
     */
    public void set(int index, E e) {
        if (index < 0 || index >= this.data.length) {
            throw new IllegalArgumentException("Index is illegal.");
        }

        this.data[index] = e;
        set(0, 0, this.data.length - 1, index, e);
    }

    /**
     * 在以treeIndex为根的线段树中更新index的值为e
     *
     * @param treeIndex
     * @param left
     * @param right
     * @param index
     * @param e
     */
    private void set(int treeIndex, int left, int right, int index, E e) {
        if (left == right) {
            this.tree[treeIndex] = e;
            return;
        }

        int mid = left + (right - left) / 2;
        // treeIndex的节点分为[left...mid]和[mid+1...right]两部分

        int leftTreeIndex = leftChild(treeIndex);
        int rightTreeIndex = rightChild(treeIndex);
        if (index >= mid + 1) {
            set(rightTreeIndex, mid + 1, right, index, e);
        } else {
            set(leftTreeIndex, left, mid, index, e);
        }

        this.tree[treeIndex] = merger.merge(tree[leftTreeIndex], tree[rightTreeIndex]);
    }

    /**
     * 获取大小
     */
    public int getSize() {
        return this.data.length;
    }

    /**
     * 根据索引获取元素
     *
     * @param index
     * @return
     */
    public E get(int index) {
        if (index < 0 || index >= this.data.length) {
            throw new IllegalArgumentException("Index is illegal.");
        }

        return this.data[index];
    }

    /**
     * 返回完全二叉树的数组表示中，一个索引所表示的元素的左孩子节点的索引
     *
     * @param index
     * @return
     */
    private int leftChild(int index) {
        return 2 * index + 1;
    }

    /**
     * 返回完全二叉树的数组表示中，一个索引所表示的元素的右孩子节点的索引
     *
     * @param index
     * @return
     */
    private int rightChild(int index) {
        return 2 * index + 2;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < tree.length; i++) {
            if (tree[i] != null) {
                sb.append(tree[i]);
            } else {
                sb.append("null");
            }

            if (i != tree.length - 1) {
                sb.append(", ");
            }
        }
        sb.append("]");

        return sb.toString();
    }
}
